package com.ipet.item.controller.backstage;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ipet.item.pojo.Category;
import com.ipet.item.service.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@Api("商标模块")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @GetMapping("/tree")
    @ApiOperation(value = "获取所有商标,并以树状结构输出")
    public ResponseEntity<List<Map<String , Object>>> getCategoryById(){
        List<Map<String, Object>> categoryTree = categoryService.findCategoryTree();
        if(CollectionUtils.isEmpty(categoryTree)){
            //404
            return  ResponseEntity.notFound().build();
        }
        return  ResponseEntity.ok(categoryTree);
    }
    @PostMapping("/saveOrUpdate")
    @ApiOperation(value = "添加或修改分类")
    @ApiImplicitParam(value = "要添加或修改的分类" , name = "category" , required = true , dataType = "Category" , paramType = "body")
    public ResponseEntity<Boolean> saveUpdate(@RequestBody Category category){
        boolean saveOrUpdate = categoryService.saveOrUpdate(category);
        return ResponseEntity.ok(saveOrUpdate);
    }
    @DeleteMapping("delete")
    @ApiOperation(value = "根据id删除商标")
    @ApiImplicitParam(value = "要删除商标id" , name = "id" , required = true , dataType = "Long" , paramType = "query")
    public ResponseEntity<Boolean> delete(Long id){
        boolean remove = categoryService.removeById(id);
        if(remove){
            categoryService.remove(new QueryWrapper<Category>().eq("parent_id" , id));
        }
        return ResponseEntity.ok(remove);
    }
    @ApiOperation(value = "通过商标名进行模糊查询")
    @ApiImplicitParam(value = "商标名关键字" , name = "name" , required = true , dataType = "String" , paramType = "query")
    @GetMapping("/treeByName")
    public ResponseEntity<List<Map<String , Object>>> findCategoryByName(String name){
        List<Map<String, Object>> mapList = categoryService.findCateGoryByNameTree(name);
        if(CollectionUtils.isEmpty(mapList)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(mapList);
    }

}
